<?php
/**
 * Created by PhpStorm.
 * User: work
 * Date: 18-7-21
 * Time: 下午6:02
 */

namespace PddWechat\Models\User\Service;


use Dai\Framework\Base\BaseService;
use Dai\Framework\Library\Log;
use Dai\Framework\Library\RedisExt;
use ElasticSearch\Exception;
use SimpleXMLElement;
use PddWechat\Library\WechatLibrary;
use PddWechat\Models\Pos\Data\PostInviteData;
use PddWechat\Models\Pos\DataObject\PostInvateDo;
use PddWechat\Models\Share\Data\ShareQrData;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\Data\UserInviteRecordData;
use PddWechat\Models\User\Data\UserOpLogData;
use PddWechat\Models\User\DataObject\UserDo;
use PddWechat\Models\User\DataObject\UserOpLogDo;

class Wechat extends BaseService
{
    public static $defaultMsg= "1. <a href='http://pdd.keepfoolish.cn/mall/index'>优惠商城</a>:拼多多专属优惠券，买的多，,购买完成平台补贴返利。\n2. <a href='http://pdd.keepfoolish.cn/mall/redpack'>天天拆红包</a>：最多100元购物津贴，分享好友，津贴翻倍,购买完成平台补贴返利。\n3. 点击下方我要赚钱， 足不出户，发发朋友圈即可赚钱。\n\t1) 点击邀请好友赚佣金，生产的图片保存到手机，然后转发到朋友圈即可。\n\t2) 我转的钱可以看到自己赚钱情况。";

    public function __construct()
    {
        $this->dataUser = new UserData();
        $this->dataOpUserLog = new UserOpLogData();
        $this->shareQrData = new ShareQrData();
    }

    /**
     * @param SimpleXMLElement $xmlObj
     * @return mixed
     */
    public function execute($xmlObj)
    {
        //获取接收消息中的参数内容
        //$toUserName = $xmlObj->ToUserName;//开发者微信号
        $fromUserName = trim($xmlObj->FromUserName);//发送方的微信号（openid）
        $msgType = trim($xmlObj->MsgType);//消息类型
        try{
            $userOpLogDo = new UserOpLogDo();
            $userOpLogDo->openId = $fromUserName;
            $userOpLogDo->event = trim($xmlObj->Event).trim($xmlObj->Content);
            $userOpLogDo->msgType = $msgType;
            $this->dataOpUserLog->insert($userOpLogDo);
        }catch (Exception $e) {
            Log::error("insert log fail, msg is ". $e->getMessage(). ",". $e->getTraceAsString());
        }

        switch ($msgType) {
            //接收文本消息
            case 'text':
                //获取文本消息的关键字
                $keyword = trim($xmlObj->Content);
                //进行关键字回复
                if( strpos($keyword, "红包") !== false ||  strpos($keyword, "永辉") !== false) {
                    return WechatLibrary::getReplyText($fromUserName, "<a href='http://pdd.keepfoolish.cn/mall/redpack?f=gzh'>点击领取最高100元购物红包</a>");
                }else {
                    return WechatLibrary::getReplyText($fromUserName, self::$defaultMsg);
                }
            case 'image':
                $mediaId = $xmlObj->MediaId;//图片消息媒体id
                return WechatLibrary::getReplyImage($fromUserName, $mediaId);
                break;
            //接收事件推送
            case 'event':
                return $this->receiveEvent($xmlObj);
            default:
                return WechatLibrary::getReplyText($fromUserName, self::$defaultMsg);
        }
    }

    //接收事件推送
    public function receiveEvent($obj)
    {
        //接收事件类型
        $event = $obj->Event;
        $openId = trim($obj->FromUserName);
        if( is_array($openId) && count($openId) > 0) {
            $openId= $openId[0];
        }

        switch ($event)
        {
            //关注事件
            case 'subscribe':
                //查询数据库有没有这个openId
                $userData = new UserData();
                $userDo = $userData->getUserByOpenId($openId);

                $status = 0; //默认没有被别人邀请
                if( strpos(trim($obj->EventKey), "qrscene_") !== false) {
                    $inviteOpenId = str_replace("qrscene_", "", trim($obj->EventKey));
                    $inviteUser = $userData -> getUserByOpenId($inviteOpenId);
                }else {
                    $inviteOpenId = "";
                    $inviteUser = null;
                }

                if($userDo == null) {
                    Log::info("invite user is new , openId is $openId ");
                    $basicUserInfo = WechatLibrary::getBasicSubscribeUserInfo($openId);
                    $userDo = $userData->insert( $basicUserInfo, 1,  $inviteOpenId, $inviteUser == null ? 0 : intval($inviteUser->id));
                    $status = 1;
                }else {
                    Log::info("invite user is not new , openId is $openId, old data is ".var_export($userDo));
                    $userDoUpdate = new UserDo();
                    $userDoUpdate->subscribe = 1;
                    $userDoUpdate->id = $userDo->id;
                    $userData->edit($userDoUpdate);
                }

                if(! empty($inviteUser)) {
                    $userInviteRecordData = new UserInviteRecordData();
                    $userInviteRecordData->insertRecord($openId, $inviteOpenId, $status );
                    if( $inviteUser->subscribe == 1) {
                        $this->sendInviteSuccTemplateMsg($userDo->userName, $inviteUser->id, $inviteUser->openId, $inviteUser->userName, $status);
                    }
                }
                return WechatLibrary::getReplyNews($openId, $this->getSendMsg());
            //取消关注事件
            case 'unsubscribe':
                $userDo = new UserDo();
                $userDo->subscribe = 0;
                $userData = new UserData();
                $userData->edit($userDo, " openId = '".$openId."'");
                return "";
            case 'CLICK':
            case 'click':
                $eventKey = $obj->EventKey;
                if( $eventKey == "invite_fr") {
                    $mediaId = $this->shareQrData->getInviteMediaId($openId);
                    if( $mediaId !== false) {
                        $this->sendInviteTemplateMsg($openId);
                        return WechatLibrary::getReplyImage($openId, $mediaId);
                    }
                }
        }
    }

    public function getSendMsg(){
        $goodsIds = RedisExt::getInstance()->get("hot_goods_ids");
        $goodsIds = explode(",", $goodsIds);

        $msgs[] = [
            'Title' => '转盘抽大奖，幸运迎免单',
            'Url' => "https://mobile.yangkeduo.com/duo_roulette.html?pid=1884871_22329699&cpsSign=CL1884871_22329699_84873959b2324bc085f9a89376d8c668&duoduo_type=2",         'Description' => '转盘抽大奖，幸运迎免单',
            'PicUrl' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536691776753&di=bd2552f6c69ed4e5535d548cfeafa719&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F26%2F19%2F45%2F83Y58PICBwr_1024.jpg',
        ];

        foreach ($goodsIds as $goodsId) {
            $goodsInfoStr = RedisExt::getInstance()->get("hot_goods_detail_$goodsId");
            if( trim($goodsInfoStr) == "") {
                continue;
            }
            $goodsInfo = json_decode($goodsInfoStr, true);
            if( $goodsInfo['goodsId'] > 0) {
                $price = round(($goodsInfo['minGroupPrice']-$goodsInfo['couponMinOrderAmount'])/1000,2);
                $promotion = round($price * $goodsInfo['promotionRate'] /1000 * 0.4,2);
                $title = "[券后价] $price 元,[返现]$promotion 元,". $goodsInfo['goodsName'];
                $msgs[] = [
                    'Title' => $title,
                    'Description'  => $title,
                    'PicUrl' => $goodsInfo['goodsImageUrl'],
                    'Url' => 'http://pdd.keepfoolish.cn/mall/goods?goodsId='.$goodsInfo['goodsId'],
                ];
            }
        }
        return $msgs;
    }

    public function sendInviteTemplateMsg($openId){
        $topColor = '#7B68EE';
        $wordColor="#173177";
        $template = [
            'touser' => $openId,
            'template_id' => "p4I34omwwPC9Y4cV4n_p6gtqXrr1sAZ1l9Er1kAjO-Q",
            'url' => "http://pdd.keepfoolish.cn/user_center.html",
            'topcolor' => $topColor,
        ];

        $template['data'] = [
            'first' => ['value' => "保存下方图片到手机，然后分享给好友，或者朋友圈。", 'color' => $wordColor],
            'keyword1' => ['value' => "图片有效期10天", 'color' => $wordColor],
            'keyword2' => ['value' => "好友购物，每一单你都可以拿到购物返现。好友邀请他的好友购物，您仍仍然有奖励。", 'color' => $wordColor],
            'keyword3' => ['value' => "如：您邀请好友A，A在平台下单，你每一单都有佣金。A邀请的任何好友,例如BC购物，您一样有奖励。\n赶紧邀请好友吧", 'color' => $wordColor],
        ];

        \Dai\Framework\Library\Log::info("openId Is ".var_export($template, true));
        \PddWechat\Library\WechatLibrary::sendTemplate(0, $openId, json_encode($template, JSON_UNESCAPED_UNICODE ));
    }

    public function sendInviteSuccTemplateMsg($nickName, $uid,  $inviteOpenId, $inviteUserName, $status) {
        $topColor = '#7B68EE';
        $wordColor="#173177";
        $template = [
            'touser' => $inviteOpenId,
            'template_id' => "FtwoU3MxmuUcli7R3VXn0BMgMR3Ox75qKzWDswwyH28",
            'url' => "http://pdd.keepfoolish.cn/user_center.html",
            'topcolor' => $topColor,
        ];

        if( $status == 0) {
            $nextMsg = "很遗憾通知您，他已经是平台老用户，所以赶紧推荐新的小伙伴吧！";
        }else {
            $nextMsg = "恭喜你，以后他购物你都会拿到购物佣金。他如果邀请了他的好友购物，你也会拿到随机奖励。赶紧让他一起货物或者让他也推荐好友吧";
        }

        $template['data'] = [
            "first" => ['value' => "$inviteUserName, 您的好友$nickName 已经接受您的邀请", 'color' => $wordColor],
            "keyword1" => ['value' => "$nickName", 'color' => $wordColor],
            'keyword2' => ['value' =>  date('Y-m-d H:i:s', time()), 'color' => $wordColor],
            'remark' => ['value' => $nextMsg , 'color' => $wordColor],
        ];
        \Dai\Framework\Library\Log::info("openiD Is ".var_export($template, true));
        \PddWechat\Library\WechatLibrary::sendTemplate($uid, $inviteOpenId, json_encode($template, JSON_UNESCAPED_UNICODE ));
    }
}
